#include "AcHandler.hpp"
#include "AsyncClient.hpp"

#include "ESPAsyncWebServer.h"
#include "WebAuthentication.h"
#include "WebResponseImpl.h"

#define TAG "WebRequest"
#define __is_param_char(c) ((c) && ((c)!='{') && ((c)!='[') && ((c)!='&') && ((c)!='='))

enum {
    PARSE_REQ_START,    // 开始解析请求
    PARSE_REQ_HEADERS,  // 解析请求头
    PARSE_REQ_BODY,     // 解析请求体
    PARSE_REQ_END,      // 解析请求结束
    PARSE_REQ_FAIL      // 解析请求失败
};

AsyncWebServerRequest::AsyncWebServerRequest(AsyncWebServer* s, AsyncClient* c)
    : _tempObject(nullptr)
    , m_client(c)
    , m_server(s)
    , m_handler(nullptr)
    , m_response(nullptr)
    , m_temp()
    , m_parseState(PARSE_REQ_START)
    , m_version(0)
    , m_method(HTTP_ANY)
    , m_url()
    , m_host()
    , m_contentType()
    , m_boundary()
    , m_authorization()
    , m_reqconntype(RCT_HTTP)
    , m_isDigest(false)
    , m_isMultipart(false)
    , m_isPlainPost(false)
    , m_expectingContinue(false)
    , m_contentLength(0)
    , m_parsedLength(0)
    , m_headers(LinkedList<AsyncWebHeader*>([](AsyncWebHeader * h)
{
    delete h;
}))
, m_params(LinkedList<AsyncWebParameter*>([](AsyncWebParameter* p)
{
    delete p;
}))
, m_pathParams(LinkedList<std::string*>([](std::string* p)
{
    delete p;
}))
, m_multiParseState(0)
, m_boundaryPosition(0)
, m_itemStartIndex(0)
, m_itemSize(0)
, m_itemName()
, m_itemFilename()
, m_itemType()
, m_itemValue()
, m_itemBuffer(0)
, m_itemBufferIndex(0)
, m_itemIsFile(false)
{
    c->set_error_event_handler([](void* r, AsyncClient * c, int8_t err) {
        auto *req = reinterpret_cast<AsyncWebServerRequest*>(r);
        req->m_onErr(err);
    },
    this
                              );
    c->set_ack_event_handler([](void* r, AsyncClient * c, size_t len, uint32_t time) {
        auto* req = reinterpret_cast<AsyncWebServerRequest*>(r);
        req->m_onAck(len, time);
    },
    this
                            );
    c->set_disconnected_event_handler([](void* r, AsyncClient * c) {
        auto* req = reinterpret_cast<AsyncWebServerRequest*>(r);
        req->m_onDisconnect();
    },
    this
                                     );
    c->set_timeout_event_handler([](void* r, AsyncClient * c, uint32_t time) {
        auto* req = reinterpret_cast<AsyncWebServerRequest*>(r);
        req->m_onTimeout(time);
    },
    this
                                );
    c->set_data_received_handler([](void* r, AsyncClient * c, void* data, size_t len) {
        auto* req = reinterpret_cast<AsyncWebServerRequest*>(r);
        req->m_onData(data, len);
    },
    this
                                );
    c->set_poll_event_handler([](void* r, AsyncClient * c) {
        auto* req = reinterpret_cast<AsyncWebServerRequest*>(r);
        req->m_onPoll();
    },
    this
                             );
}

AsyncWebServerRequest::~AsyncWebServerRequest()
{
    m_headers.free();
    m_params.free();
    m_pathParams.free();
    m_interestingHeaders.free();

    if (m_response != nullptr) {
        delete m_response;
        m_response = nullptr;
    }

    if (_tempObject != nullptr) {
        free(_tempObject);
        _tempObject = nullptr;
    }
}

void AsyncWebServerRequest::m_onData(void* buf, size_t len)
{
    size_t i;

    while (true) {
        if (m_parseState < PARSE_REQ_BODY) {    // 处理请求行和请求头
            auto *str = (char*)buf;
            for (i = 0; i < len; i++) {
                if (str[i] == '\n') {
                    break;
                }
            }

            if (i >= len) { // 没有找到换行符，将buf添加到m_temp中
                char ch = str[len - 1];
                str[len - 1] = 0;
                m_temp.reserve(m_temp.length() + len + 1);
                m_temp.append(str);
                m_temp.push_back(ch);
            } else {        // 找到换行符
                str[i] = 0;
                m_temp.append(str);
                trim(m_temp);          // 去除两端的空白字符
                m_parseLine();         // 处理得到的一行请示行/头
                // 移动buf指针
                if (++i < len) {
                    buf = str + i;
                    len -= i;
                    continue;
                }
            }
        } else if (m_parseState == PARSE_REQ_BODY) { // 处理请求体
            const bool needParse = (m_handler && !(m_handler->isRequestHandlerTrivial()));
            if (m_isMultipart) {
                if (needParse) {
                    for (size_t i = 0; i < len; i++) {
                        m_parseMultipartPostByte(static_cast<uint8_t*>(buf)[i], i == len - 1);
                        m_parsedLength ++;
                    }
                } else {
                    m_parsedLength += len;
                }
            } else {
                if (m_parsedLength == 0) {
                    if (m_contentType.starts_with("application/x-www-form-urlencoded")) {
                        m_isPlainPost = true;
                    } else if (m_contentType == "text/plain" && __is_param_char(((char *)buf)[0])) {
                        size_t i = 0;
                        while (i < len && __is_param_char(((char *)buf)[i++])) {
                            ;
                        }
                        if (i < len && ((char *)buf)[i - 1] == '=') {
                            m_isPlainPost = true;
                        }
                    }
                }

                if (!m_isPlainPost) {   // 非表单数据处理
                    if (m_handler) {
                        m_handler->handleBody(this, (uint8_t*)buf, len, m_parsedLength, m_contentLength);
                    }
                    m_parsedLength += len;
                } else if (needParse) {
                    for (size_t i = 0; i < len; i++) {
                        m_parsedLength++;
                        m_parsePlainPostChar(((uint8_t*)buf)[i]);
                    }
                } else {
                    m_parsedLength += len;
                }
            }
            if (m_parsedLength == m_contentLength) {
                m_parseState = PARSE_REQ_END;
                if (m_handler) {
                    m_handler->handleRequest(this);
                } else {
                    send(501);
                }
            }
        }
        break;
    }
}

/// @brief 根据解析状态机，对每一行（m_temp）进行解析
void AsyncWebServerRequest::m_parseLine()
{
    /*
     *   请求行
     *   请求头1: value1
     *   ...
     *   \r\n  // 空行
     *   [请求体（可选）]
    */
    // 处理请求行
    if (m_parseState == PARSE_REQ_START) {
        if (m_temp.length()) {
            m_parseReqHead();
            m_parseState = PARSE_REQ_HEADERS;
        } else {
            m_parseState = PARSE_REQ_FAIL;
            m_client->close();
            ESP_LOGE(TAG, "解析请求失败.");
        }
        return;
    }

    // 处理请求头
    if (m_parseState == PARSE_REQ_HEADERS) {
        if (m_temp.length()) {  //  要处理的行不是空行，解析请求头
            m_parseReqHeader();
        } else {                // 要处理的行为空行，请求头解析结束
            m_server->_rewriteRequest(this);   // 重写请求
            m_server->_attachHandler(this);    // 绑定处理函数
            m_removeNotInterestingHeaders();   // 过滤不关心的请求头
            if (m_expectingContinue) {  // 发送临时响应
                const char* response = "HTTP/1.1 100 Continue\r\n\r\n";
                m_client->write(response, strlen(response));
            }
            if (m_contentLength) {
                m_parseState = PARSE_REQ_BODY;
            } else {
                m_parseState = PARSE_REQ_END;
                if (m_handler) {
                    m_handler->handleRequest(this);
                } else {
                    send(501);
                }
            }
        }
    }
}

/// @brief 执行断开连接时的程序
void AsyncWebServerRequest::m_onDisconnect()
{
    if (m_onDisconnectfn != nullptr) {
        m_onDisconnectfn();
    }
    m_server->_handleDisconnect(this);
}

/// @brief 对数据进行确认
/// @param len
/// @param time
void AsyncWebServerRequest::m_onAck(size_t len, uint64_t time)
{
    if (m_response != nullptr) {
        if (!m_response->_finished()) {
            m_response->_ack(this, len, time);
        } else {
            auto* r = m_response;
            m_response = nullptr;
            delete r;
        }
    }
}

void AsyncWebServerRequest::m_onPoll()
{
    if (m_response != nullptr
            && m_client != nullptr
            && m_client->get_send_buffer_size()
            && !(m_response->_finished())) {
        m_response->_ack(this, 0, 0);
    }
}

/// @brief 解析POST请求中的纯文本数据，将其转换为键值对参数后存储
/// @param data
void AsyncWebServerRequest::m_parsePlainPostChar(uint8_t data)
{
    if (data && (char)data != '&') {
        m_temp.push_back((char)data);
    }
    if (!data || (char)data == '&' || m_parsedLength == m_contentLength) {
        std::string name = "body";
        std::string value = m_temp;
        size_t equalIndex = m_temp.find('=');
        if (!m_temp.starts_with("{") && !m_temp.starts_with("[") && equalIndex != std::string::npos) {
            name = m_temp.substr(0, equalIndex);
            value = m_temp.substr(equalIndex + 1);
        }
        m_addParam(new AsyncWebParameter(urlDecode(name), urlDecode(value), true));
        m_temp.clear();
    }
}

// 多表单处理状态
enum {
    EXPECT_BOUNDARY,
    PARSE_HEADERS,
    WAIT_FOR_RETURN1,
    EXPECT_FEED1,
    EXPECT_DASH1,
    EXPECT_DASH2,
    BOUNDARY_OR_DATA,
    DASH3_OR_RETURN2,
    EXPECT_FEED2,
    PARSING_FINISHED,
    PARSE_ERROR
};
/// @brief 解析 HTTP 多表单数据，处理文件上传、将参数添加到请求中。
/// @param data 要处理的数据
/// @param last 是否为最后一个字节
void AsyncWebServerRequest::m_parseMultipartPostByte(uint8_t data, bool last)
{
#define itemWriteByte(b) \
    do { \
        m_itemSize++; \
        if(m_itemIsFile) \
            m_handleUploadByte(b, last); \
        else \
            m_itemValue.push_back((char)(b)); \
        } \
    while(0)

    // 根据处理的数据量条件初始化各个参数
    if (!m_parsedLength) {
        m_multiParseState = EXPECT_BOUNDARY;
        m_temp.clear();
        m_itemName.clear();
        m_itemFilename.clear();
        m_itemType.clear();
    }

    /*
    ------WebKitFormBoundary7MA4YWxkTrZu0gW
    Content-Disposition: form-data; name="username"

    JohnDoe
    ------WebKitFormBoundary7MA4YWxkTrZu0gW
    Content-Disposition: form-data; name="uploadFile"; filename="example.png"
    Content-Type: image/png
    */
    size_t boundaryLength = m_boundary.length();
    switch (m_multiParseState) {
    case WAIT_FOR_RETURN1:  // 等待特殊字符\r
        if (data != '\r') {
            itemWriteByte(data);
        } else {
            m_multiParseState = EXPECT_FEED1;
        }
        break;
    case EXPECT_BOUNDARY:   // 比较分界字符串
        if (m_parsedLength < 2 && data != '-') { // 前2字节固定为'-'
            m_multiParseState = PARSE_ERROR;
            return;
        } else if (m_parsedLength - 2 < boundaryLength && m_boundary.c_str()[m_parsedLength - 2] != data) {
            m_multiParseState = PARSE_ERROR;
            return;
        } else if (m_parsedLength - 2 == boundaryLength && data != '\r') { // 查找结尾标志符
            m_multiParseState = PARSE_ERROR;
            return;
        } else if (m_parsedLength - 3 == boundaryLength) {
            if (data != '\n') {
                m_multiParseState = PARSE_ERROR;
                return;
            }
            m_multiParseState = PARSE_HEADERS;
            m_itemIsFile = false;   // 重置此参数
        }
        break;
    case PARSE_HEADERS:     // 处理多表单的头信息
        if ((char)data != '\r' && (char)data != '\n') {
            m_temp.push_back((char)data);   // 读入一行数据
        }
        if ((char)data == '\n') {
            if (m_temp.length()) {
                if (m_temp.length() > 12 && equalsIgnoreCase(m_temp.substr(0, 12), "Content-Type")) {
                    m_itemType = m_temp.substr(14);
                    m_itemIsFile = true;
                } else if (m_temp.length() > 19 && equalsIgnoreCase(m_temp.substr(0, 19), "Content-Disposition")) {
                    m_temp = m_temp.substr(m_temp.find(';') + 2);
                    while (m_temp.find(';') != std::string::npos) {
                        size_t pos1 = m_temp.find('=');
                        size_t pos2 = m_temp.find(';');
                        std::string name = m_temp.substr(0, pos1);
                        if (name == "name") {
                            m_itemName = m_temp.substr(pos2 + 1, pos2 - pos1 - 1);  //..........
                        } else if (name == "filename") {
                            m_itemFilename = m_temp.substr(pos2 + 1, pos2 - pos1 - 1);
                            m_itemIsFile = true;
                        }
                        m_temp = m_temp.substr(pos2 + 2);
                    }
                    size_t equalIndex = m_temp.find('=');
                    std::string name = m_temp.substr(0, equalIndex);
                    if (name == "name") {
                        m_itemName = m_temp.substr(equalIndex + 2, m_temp.length() - equalIndex - 1);   // .......
                    } else if (name == "filename") {
                        m_itemFilename = m_temp.substr(equalIndex + 2, m_temp.length() - equalIndex - 1);
                        m_itemIsFile = true;
                    }
                }
                m_temp.clear();
            } else {    // 遇到空行转至下一阶段
                m_multiParseState = WAIT_FOR_RETURN1;
                m_itemSize = 0;
                m_itemStartIndex = m_parsedLength;
                m_itemValue.clear();
                if (m_itemIsFile) {
                    if (m_itemBuffer) {
                        free(m_itemBuffer);
                    }
                    m_itemBuffer = (uint8_t*)malloc(1460);
                    if (m_itemBuffer == nullptr) {
                        m_multiParseState = PARSE_ERROR;
                        return;
                    }
                    m_itemBufferIndex = 0;
                }
            }
        }
        break;
    case EXPECT_FEED1:      // 等待特殊字符\n
        if (data != '\n') {
            m_multiParseState = WAIT_FOR_RETURN1;
            itemWriteByte('\r');
            m_parseMultipartPostByte(data, last);
        } else {
            m_multiParseState = EXPECT_DASH1;
        }
        break;
    case EXPECT_DASH1:
        if (data != '-') {
            m_multiParseState = WAIT_FOR_RETURN1;
            itemWriteByte('\r');
            itemWriteByte('\n');
            m_parseMultipartPostByte(data, last);
        } else {
            m_multiParseState = EXPECT_DASH2;
        }
        break;
    case EXPECT_DASH2:
        if (data != '-') {
            m_multiParseState = WAIT_FOR_RETURN1;
            itemWriteByte('\r');
            itemWriteByte('\n');
            itemWriteByte('-');
            m_parseMultipartPostByte(data, last);
        } else {
            m_multiParseState = BOUNDARY_OR_DATA;
            m_boundaryPosition = 0;
        }
        break;
    case BOUNDARY_OR_DATA:  //判断边界字符
        if (m_boundaryPosition < boundaryLength && m_boundary.c_str()[m_boundaryPosition] != data) {
            m_multiParseState = WAIT_FOR_RETURN1;
            itemWriteByte('\r');
            itemWriteByte('\n');
            itemWriteByte('-');
            itemWriteByte('-');
            for (uint8_t i = 0; i < m_boundaryPosition; i++) {
                itemWriteByte(m_boundary.c_str()[i]);
            }
            m_parseMultipartPostByte(data, last);
        } else if (m_boundaryPosition == boundaryLength - 1) {
            m_multiParseState = DASH3_OR_RETURN2;
            if (m_itemIsFile) {    //
                if (m_itemSize) {
                    if (m_handler) {
                        m_handler->handleUpload(this, m_itemFilename, m_itemSize - m_itemBufferIndex, m_itemBuffer, m_itemBufferIndex, true);
                    }
                    m_itemBufferIndex = 0;
                    m_addParam(new AsyncWebParameter(m_itemName, m_itemFilename, true, true, m_itemSize));
                }
                free(m_itemBuffer);
                m_itemBuffer = nullptr;
            } else {            // 将请求的字段和值添加到请求参数中
                m_addParam(new AsyncWebParameter(m_itemName, m_itemValue, true));
            }
        } else {
            m_boundaryPosition++;
        }
        break;
    case DASH3_OR_RETURN2:      // 检查是否到最终结束符
        if (data == '-' && (m_contentLength - m_parsedLength - 4) != 0) {
            m_contentLength = m_parsedLength + 4;
        }
        if (data == '\r') {
            m_multiParseState = EXPECT_FEED2;
        } else if (data == '-' && m_contentLength == (m_parsedLength + 4)) {
            m_multiParseState = PARSING_FINISHED;
        } else {
            m_multiParseState = WAIT_FOR_RETURN1;
            itemWriteByte('\r');
            itemWriteByte('\n');
            itemWriteByte('-');
            itemWriteByte('-');
            uint8_t i;
            for (i = 0; i < boundaryLength; i++) {
                itemWriteByte(m_boundary.c_str()[i]);
            }
            m_parseMultipartPostByte(data, last);
        }
        break;
    case EXPECT_FEED2:
        if (data == '\n') {
            m_multiParseState = PARSE_HEADERS;
            m_itemIsFile = false;
        } else {
            m_multiParseState = WAIT_FOR_RETURN1;
            itemWriteByte('\r');
            itemWriteByte('\n');
            itemWriteByte('-');
            itemWriteByte('-');
            for (uint8_t i = 0; i < boundaryLength; i++) {
                itemWriteByte(m_boundary.c_str()[i]);
            }
            itemWriteByte('\r');
            m_parseMultipartPostByte(data, last);
        }
        break;
    }
}

/// @brief 将上传的数据存储到缓冲区，并在缓冲区满或传输结束时触发处理器（如AsyncWebHandler）进行处理。
/// @param data
/// @param last
void AsyncWebServerRequest::m_handleUploadByte(uint8_t data, bool last)
{
    m_itemBuffer[m_itemBufferIndex++] = data;

    if (last || m_itemBufferIndex == 1460) {
        //................如果上传文件的验证在上传之后如何处理？
        if (m_handler) {
            m_handler->handleUpload(this, m_itemFilename, m_itemSize - m_itemBufferIndex, m_itemBuffer, m_itemBufferIndex, false);
        }
        m_itemBufferIndex = 0;
    }
}

/// @brief 添加路径参数
/// @param param
void AsyncWebServerRequest::m_addPathParam(const char* param)
{
    m_pathParams.add(new std::string(param));
}

/// @brief 获取指定索引头部的名称
/// @param index
/// @return
const std::string &AsyncWebServerRequest::headerName(size_t index) const
{
    auto* header = getHeader(index);
    return header == nullptr ? std::string() : header->name();
}

/// @brief 获取指定索引的请求的头部值
/// @param index
/// @return
const std::string &AsyncWebServerRequest::header(size_t index) const
{
    auto* header = getHeader(index);
    return header == nullptr ? std::string() : header->value();
}

/// @brief 获取请求中指定名字的头部值
/// @param name
/// @return
const std::string &AsyncWebServerRequest::header(const char* name) const
{
    auto* header = getHeader(std::string(name));
    return header == nullptr ? std::string() : header->value();
}

/// @brief 检查是否含有指定名字的参数
/// @param name
/// @return
bool AsyncWebServerRequest::hasArg(const char* name) const
{
    for (const auto &arg : m_params) {
        if (arg->name() == name) {
            return true;
        }
    }

    return false;
}

/// @brief 获取指定索引参数的参数名
/// @param index
/// @return
const std::string &AsyncWebServerRequest::argName(size_t index) const
{
    AsyncWebParameter* param = getParam(index);
    return param != nullptr ? param->name() : std::string();
}

/// @brief 获取指定索引参数的参数值
/// @param index
/// @return
const std::string &AsyncWebServerRequest::arg(size_t index) const
{
    AsyncWebParameter* param = getParam(index);
    return param != nullptr ? param->value() : std::string();
}

/// @brief 从参数列表中获取指定名称的HTTP参数值
/// @param name 参数名
/// @return
const std::string &AsyncWebServerRequest::arg(const std::string &name) const
{
    if (name.empty()) {
        return std::string();
    }
    for (const auto &arg : m_params) {
        if (arg->name() == name) {
            return arg->value();
        }
    }
    return std::string();
}

/// @brief 获取请求参数个数
/// @return
size_t AsyncWebServerRequest::args() const
{
    return params();
}

/// @brief 获取参数列表中指定索引的参数
/// @param index 参数索引
/// @return
AsyncWebParameter* AsyncWebServerRequest::getParam(size_t index) const
{
    auto param = m_params.nth(index);
    return param != nullptr ? *param : nullptr;
}

/// @brief 获取HTTP请求中特定的参数.......可优化（bool放前面）
/// @param name
/// @param post
/// @param file
/// @return
AsyncWebParameter* AsyncWebServerRequest::getParam(const std::string &name, bool post, bool file) const
{
    if (name.empty()) {
        return nullptr;
    }
    for (const auto &param : m_params) {
        if (param->name() == name && param->isPost() == post && param->isFile() == file) {
            return param;
        }
    }
    return nullptr;
}

/// @brief 检查HTTP请求中是否存在指定的参数.....可优化（将bool放前面）
/// @param name 参数名
/// @param post 为TRUE时，检查POST请求体中是否有name字段
/// @param file 为TRUE时，检查文件上传名字是否为name
/// @return
bool AsyncWebServerRequest::hasParam(const std::string &name, bool post, bool file) const
{
    if (name.empty()) {
        return false;
    }
    for (const auto &param : m_params) {
        if (param->name() == name && param->isPost() == post && param->isFile() == file) {
            return true;
        }
    }
    return false;
}

/// @brief 获取请求参数个数
/// @return
size_t AsyncWebServerRequest::params() const
{
    return m_params.length();
}

/// @brief 获取头部列表中指定索引的头部
/// @param index 要获取的头部的索引
/// @return
AsyncWebHeader* AsyncWebServerRequest::getHeader(size_t index) const
{
    auto header = m_headers.nth(index);
    return header != nullptr ? *header : nullptr;
}

/// @brief 根据指定的名称获取响应头部行
/// @param name
/// @return 未找到返回nullptr
AsyncWebHeader* AsyncWebServerRequest::getHeader(const std::string &name) const
{
    if (name.empty()) {
        return nullptr;
    }

    for (const auto &header : m_headers) {
        if (equalsIgnoreCase(header->name(), name)) {
            return header;
        }
    }
    return nullptr;
}

/// @brief 检查是否包含某个响应头
/// @param name 响应头名称
/// @return
bool AsyncWebServerRequest::hasHeader(const std::string &name) const
{
    if (name.empty()) {
        return false;
    }
    for (const auto &header : m_headers) {
        if (equalsIgnoreCase(header->name(), name)) {
            return true;
        }
    }
    return false;
}

/// @brief 获取响应头的个数
/// @return
size_t AsyncWebServerRequest::headers() const
{
    return m_headers.length();
}

/// @brief 过滤不关心的请求头(根据m_interestingHeaders配置，去除m_headers的头)
void AsyncWebServerRequest::m_removeNotInterestingHeaders()
{
    if (m_interestingHeaders.containsIgnoreCase("ANY")) {
        return;
    }
    for (const auto &header : m_headers) {
        if (!m_interestingHeaders.containsIgnoreCase(header->name().c_str())) {
            m_headers.remove(header);
        }
    }
}

bool strContains(std::string src, std::string find, bool ignoreCase = true)
{
    size_t pos = 0, i = 0;
    const size_t slen = src.length();
    const size_t flen = find.length();

    if (slen < flen) {
        return false;
    }
    while (pos <= (slen - flen)) {
        for (i = 0; i < flen; i++) {
            if (ignoreCase) {
                if (src[pos + i] != find[i]) {
                    i = flen + 1;    // no match
                }
            } else if (tolower(src[pos + i]) != tolower(find[i])) {
                i = flen + 1;    // no match
            }
        }
        if (i == flen) {
            return true;
        }
        pos++;
    }
    return false;
}

/// @brief 解析解析每一行请求头中的字符串（如 Host, Content-Type, Authorization 等），并将其存储到类的成员变量m_headers中，以便后续处理（如路由、认证、解析请求体等）
/// @return
/// 请求头格式>>>请求头1: value1
bool AsyncWebServerRequest::m_parseReqHeader()
{
    size_t index = m_temp.find(':');
    if (index != std::string::npos) {
        std::string name = m_temp.substr(0, index);
        std::string value = m_temp.substr(index + 2);

        if (equalsIgnoreCase(name, "Host")) {
            // Host: example.com
            m_host = value;
        } else if (equalsIgnoreCase(name, "Content-Type")) {
            // Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
            m_contentType = value.substr(0, value.find(';'));
            if (value.starts_with("multipart")) {
                m_boundary = value.substr(value.find('=') + 1);
                m_boundary.erase(
                              std::remove(
                                  m_boundary.begin(),
                                  m_boundary.end(),
                                  '"'
                              ),
                              m_boundary.end()
                          );
                m_isMultipart = true;
            }
        } else if (equalsIgnoreCase(name, "Content-Length")) {
            // Content-Length: 723
            m_contentLength = atoi(value.c_str());
        } else if (equalsIgnoreCase(name, "Expect") && value == "100-continue") {
            // Expect: 100-continue
            m_expectingContinue = true;
        } else if (equalsIgnoreCase(name, "Authorization")) {
            // Authorization: Basic eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.XXXXXXXXXXXXXXXXXX
            if (value.length() > 5 && equalsIgnoreCase(value.substr(0, 5), "Basic")) {
                m_authorization = value.substr(6);
            } else if (value.length() > 6 && equalsIgnoreCase(value.substr(0, 6), "Digest")) {
                m_isDigest = true;
                m_authorization = value.substr(7);
            }
        } else {
            if (equalsIgnoreCase(name, "Upgrade") && equalsIgnoreCase(value, "websocket")) {
                m_reqconntype = RCT_WS;
            } else {
                if (equalsIgnoreCase(name, "Accept") && strContains(value, "text/event-stream", false)) {
                    m_reqconntype = RCT_EVENT;
                }
            }
        }
        m_headers.add(new AsyncWebHeader(name, value));
    }
    m_temp = std::string();
    return true;
}

/// @brief 超时回调函数：关闭连接
/// @param time
void AsyncWebServerRequest::m_onTimeout(uint64_t time)
{
    m_client->close();
}

/// @brief 设置断开连接时的回调函数
/// @param fn
void AsyncWebServerRequest::onDisconnect(ArDisconnectHandler fn)
{
    m_onDisconnectfn = fn;
}

/// @brief 错误回调函数
/// @param error
void AsyncWebServerRequest::m_onErr(err_t error)
{}

/// @brief 添加请求参数到m_params成员变量
/// @param p 请求参数
void AsyncWebServerRequest::m_addParam(AsyncWebParameter *p)
{
    m_params.add(p);
}

/// @brief 解析请求行的参数，调用相关方法存储到成员对象中
/// @param params 参数字符串
void AsyncWebServerRequest::m_addGetParams(const std::string &params)
{
    size_t start = 0;

    while (start < params.length()) {
        size_t end = params.find('&', start);
        if (end == std::string::npos) {
            end = params.length();
        }
        size_t equal = params.find('=', start);
        if (equal == std::string::npos || equal > end) {
            equal = end;
        }
        std::string name = params.substr(start, equal - start);
        std::string value = equal + 1 < end ? params.substr(equal + 1, end - equal - 1) : std::string();
        m_addParam(new AsyncWebParameter(urlDecode(name), urlDecode(value)));
        start = end + 1;
    }
}

/// @brief 解析 HTTP 请求行（Request Line），设置相应参数请求方法（如 GET/POST）、URL 路径、查询参数和 HTTP 版本。
/// 请求行实例："GET /search?query=ESP32&category=development HTTP/1.1"
bool AsyncWebServerRequest::m_parseReqHead()
{
    size_t spaceIndex1 = m_temp.find_first_of(' ');
    size_t spaceIndex2 = m_temp.find(' ', spaceIndex1 + 1);
    size_t questionMarkIndex = m_temp.find('?', spaceIndex1);

    std::string method = m_temp.substr(0, spaceIndex1);
    size_t urlLen;
    if (questionMarkIndex != std::string::npos) {   // 存在参数
        urlLen = questionMarkIndex - spaceIndex1 - 1;
        std::string param = m_temp.substr(questionMarkIndex + 1, spaceIndex2 - questionMarkIndex - 1);
        m_addGetParams(param);
    } else {
        urlLen = spaceIndex2 - spaceIndex1 - 1;
    }
    std::string url = m_temp.substr(spaceIndex1 + 1, urlLen);
    m_url = urlDecode(url);

    // 设置协义版本
    if (!m_temp.substr(spaceIndex2 + 1).starts_with("HTTP/1.0")) {
        m_version = 1;
    }
    m_temp.clear();

    // 设置请求方法
    if (method == "GET") {
        m_method = HTTP_GET;
    } else if (method == "POST") {
        m_method = HTTP_POST;
    } else if (method == "DELETE") {
        m_method = HTTP_DELETE;
    } else if (method == "PUT") {
        m_method = HTTP_PUT;
    } else if (method == "PATCH") {
        m_method = HTTP_PATCH;
    } else if (method == "HEAD") {
        m_method = HTTP_HEAD;
    } else if (method == "OPTIONS") {
        m_method = HTTP_OPTIONS;
    }

    return true;
}

/// @brief 对URL编码的字符串进行解码
/// @param text 需要解码的URL编码字符串
/// @return 解码后的字符串
std::string AsyncWebServerRequest::urlDecode(const std::string &text) const
{
    char temp[] = "0x00";
    char decodedChar, encodedChar;
    size_t textLength = text.length();
    size_t i = 0;

    std::string decoded;
    decoded.reserve(textLength);      // 解码字符先预留足够空间（防止反复调整内存大小）

    while (i < textLength) {
        encodedChar = text[i++];
        if ((encodedChar == '%') && (i + 1 < textLength)) {
            temp[2] = text[i++];
            temp[3] = text[i++];
            decodedChar = strtol(temp, nullptr, 16);    // 直接使用后两位
        } else if (encodedChar == '+') {
            decodedChar = ' ';
        } else {
            decodedChar = encodedChar;
        }
        decoded.push_back(decodedChar);
    }
    return decoded;
}

/// @brief 调用相应派生类的_respond()函数，将响应发送出去
/// @param response 响应基类指针（传递参数可能是派生类）
void AsyncWebServerRequest::send(AsyncWebServerResponse* response)
{
    m_response = response;
    if (m_response == nullptr) {
        m_client->close(true);
        ESP_LOGW(TAG, "响应内容为空连接已关闭1");
        m_onDisconnect();
        ESP_LOGW(TAG, "响应内容为空连接已关闭");
        return;
    }
    if (m_response->_sourceValid()) {
        m_client->set_rx_timeout_second(0);
        m_response->_respond(this);
    } else {
        delete m_response;
        m_response = nullptr;
        send(500);
    }
}

/// @brief 发送一个基本的响应
/// @param code HTTP状态码
/// @param contentType 内容类型
/// @param content 内容
void AsyncWebServerRequest::send(int code, const std::string &contentType, const std::string &content)
{
    send(beginResponse(code, contentType, content));
}

/// @brief 发送一个文件响应
/// @param path
/// @param contentType
/// @param download
/// @param callback
void AsyncWebServerRequest::send(const std::string &path, const std::string &contentType, bool download, AwsTemplateProcessor callback)
{
    if (FILE_EXISTS(path.c_str()) || (!download && FILE_EXISTS(std::string(path + ".gz").c_str()))) {
        send(beginResponse(path, contentType, download, callback));
    } else {
        send(404);
    }
}

/// @brief 将请求重定向到新的位置..........可能解释有问题
/// @param url 资源重定向后的路径
void AsyncWebServerRequest::redirect(const std::string &url)
{
    auto* response = beginResponse(302);
    response->addHeader("Location", url);
    send(response);
}

/// @brief 向关注的头请求头列表中添加头部
/// @param name
void AsyncWebServerRequest::addInterestingHeader(const std::string &name)
{
    if (!m_interestingHeaders.containsIgnoreCase(name)) {
        m_interestingHeaders.add(name);
    }
}

/// @brief 设置处理该请求的处理器
/// @param handler
void AsyncWebServerRequest::setHandler(AsyncWebHandler* handler)
{
    m_handler = handler;
}

/// @brief 向客户端发送HTTP 401 Unauthorized响应，附加WWW-Authenticate头，要求进行身份认证
/// @param realm 认证域（标识受保护资源的范围）
/// @param isDigest
void AsyncWebServerRequest::requestAuthentication(const char* realm, bool isDigest)
{
    AsyncWebServerResponse* r = beginResponse(401);
    if (!isDigest) {
        if (realm == nullptr) {
            r->addHeader("WWW-Authenticate", R"(Basic realm="Login Required")");
        } else {
            std::string header = R"(Basic realm=")";
            header.append(realm);
            header.push_back('"');
            r->addHeader("WWW-Authenticate", header);
        }
    } else {
        std::string header = "Digest ";
        header.append(requestDigestAuthentication(realm));
        r->addHeader("WWW-Authenticate", header);
    }
    send(r);
}

/// @brief 构建分片响应
/// @param contentType
/// @param callback
/// @param templateCallback
/// @return
AsyncWebServerResponse* AsyncWebServerRequest::beginChunkedResponse(const std::string &contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback)
{
    if (m_version) {
        return new AsyncChunkedResponse(contentType, callback, templateCallback);
    }
    return new AsyncCallbackResponse(contentType, 0, callback, templateCallback);
}

/// @brief 构造调用响应
/// @param contentType
/// @param len
/// @param callback
/// @param templateCallback
/// @return
AsyncWebServerResponse* AsyncWebServerRequest::beginResponse(const std::string &contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback)
{
    if (callback != nullptr) {
        return new AsyncCallbackResponse(contentType, len, callback, templateCallback);
    }
    return nullptr;
}

/// @brief 构造文件响应
/// @param path 文件路径
/// @param contentType
/// @param download
/// @param callback
/// @return
AsyncWebServerResponse* AsyncWebServerRequest::beginResponse(const std::string &path, const std::string &contentType, bool download, AwsTemplateProcessor callback)
{
    if (FILE_EXISTS(path.c_str()) || (!download && FILE_EXISTS(std::string(path + ".gz").c_str()))) {
        return new AsyncFileResponse(path, contentType, download, callback);
    }
    return nullptr;
}

/// @brief 用于构建基本响应
/// @param code 响应状态码
/// @param contentType 内容类型
/// @param content 响应内容
/// @return
AsyncWebServerResponse* AsyncWebServerRequest::beginResponse(int code, const std::string &contentType, const std::string &content)
{
    return new AsyncBasicResponse(code, contentType, content);
}

/// @brief 验证HTTP请求的身份信息
/// @param username 预期的用户名
/// @param password 预期的密码
/// @param realm Digest认证的领域（用于WWW-Authenticate质询）
/// @param passwordIsHash 密码是否为哈希值
/// @return
bool AsyncWebServerRequest::authenticate(const char* username, const char* password, const char* realm, bool passwordIsHash)
{
    if (m_authorization.length()) {
        if (m_isDigest) {
            return checkDigestAuthentication(m_authorization.c_str(),
                                             methodToString(),
                                             username,
                                             password,
                                             realm,
                                             passwordIsHash,
                                             nullptr,
                                             nullptr,
                                             nullptr
                                            );
        } else if (!passwordIsHash) {
            return checkBasicAuthentication(
                       m_authorization.c_str(),
                       username,
                       password
                   );
        } else {
            return m_authorization == std::string(password);
        }
    }

    return false;
}

/// @brief 进行用户信息认证
/// @param hash
/// @return
bool AsyncWebServerRequest::authenticate(const char * hash)
{
    if (!m_authorization.length() || hash == nullptr) {
        return false;
    }

    if (m_isDigest) {
        std::string hash_str = std::string(hash);
        size_t separator = hash_str.find(':');
        if (separator == std::string::npos) {
            return false;
        }
        std::string username = hash_str.substr(0, separator);
        hash_str = hash_str.substr(separator + 1);
        separator = hash_str.find(':');
        if (separator == std::string::npos) {
            return false;
        }
        std::string realm = hash_str.substr(0, separator);
        hash_str = hash_str.substr(separator + 1);
        return checkDigestAuthentication(
                   m_authorization.c_str(),
                   methodToString(),
                   username.c_str(),
                   hash_str.c_str(),
                   realm.c_str(),
                   true,
                   nullptr,
                   nullptr,
                   nullptr
               );
    }

    return m_authorization == std::string(hash);
}

/// @brief 获取关联的客户端对象
/// @return
AsyncClient* AsyncWebServerRequest::client()
{
    return m_client;
}

/// @brief 获取HTTP版本
/// @return
uint8_t AsyncWebServerRequest::version() const
{
    return m_version;
}

/// @brief 获取请求方法
/// @return
WebRequestMethodComposite AsyncWebServerRequest::method() const
{
    return m_method;
}

/// @brief 获取请求的URL路径
/// @return
const std::string &AsyncWebServerRequest::url() const
{
    return m_url;
}

/// @brief 获取请求的目标主机（域名/IP），用于虚拟主机路由
/// @return
const std::string &AsyncWebServerRequest::host() const
{
    return m_host;
}

/// @brief 获取请求体的媒体类型（如application/json），指导数据解析
/// @return
const std::string &AsyncWebServerRequest::contentType() const
{
    return m_contentType;
}

/// @brief 获取请求体的长度
/// @return
size_t AsyncWebServerRequest::contentLength() const
{
    return m_contentLength;
}

/// @brief 判断请求是否使用multipart/form-data格式
/// @return
bool AsyncWebServerRequest::multipart() const
{
    return m_isMultipart;
}

/// @brief 获取字符形式的请求方法
/// @return
const char* AsyncWebServerRequest::methodToString() const
{
    if (m_method == HTTP_ANY) {
        return "ANY";
    } else if (m_method & HTTP_GET) {
        return "GET";
    } else if (m_method & HTTP_POST) {
        return "POST";
    } else if (m_method & HTTP_DELETE) {
        return "DELETE";
    } else if (m_method & HTTP_PUT) {
        return "PUT";
    } else if (m_method & HTTP_PATCH) {
        return "PATCH";
    } else if (m_method & HTTP_HEAD) {
        return "HEAD";
    } else if (m_method & HTTP_OPTIONS) {
        return "OPTIONS";
    }

    return "UNKNOWN";
}

/// @brief 将请求的连接类型转化为字符形式
/// @return
const char* AsyncWebServerRequest::requestedConnTypeToString() const
{
    switch (m_reqconntype) {
    case RCT_NOT_USED: return "RCT_NOT_USED";
    case RCT_DEFAULT: return "RCT_DEFAULT";
    case RCT_HTTP: return "RCT_HTTP";
    case RCT_WS: return "RCT_WS";
    case RCT_EVENT: return "RCT_EVENT";
    default:    return "ERROR";
    }
}

/// @brief 获取连接类型
/// @return
RequestedConnectionType AsyncWebServerRequest::requestedConnType() const
{
    return m_reqconntype;
}

/// @brief 检查当前请求的连接类型是否符合传入的预期类型
/// @param erct1
/// @param erct2
/// @param erct3
/// @return
bool AsyncWebServerRequest::isExpectedRequestedConnType(RequestedConnectionType erct1, RequestedConnectionType erct2, RequestedConnectionType erct3)
{
    bool res = false;
    if ((erct1 != RCT_NOT_USED) && (erct1 == m_reqconntype)) {
        res = true;
    }
    if ((erct2 != RCT_NOT_USED) && (erct2 == m_reqconntype)) {
        res = true;
    }
    if ((erct3 != RCT_NOT_USED) && (erct3 == m_reqconntype)) {
        res = true;
    }
    return res;
}
